package com.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.myblog.constant.CodeType;
import com.myblog.mapper.FriendLinkMapper;
import com.myblog.model.FriendLink;
import com.myblog.service.FriendLinkService;
import com.myblog.utils.DataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FriendLinkServiceImpl implements FriendLinkService {

    @Autowired
    private FriendLinkMapper friendLinkMapper;

    /**
     * 查找所有友链
     * @return
     */
    @Override
    public DataMap searchAllFriendLink() {
        List<FriendLink> friendLinks = friendLinkMapper.selectAllFriend();

        List<JSONObject> result = new ArrayList<>();
        for (FriendLink friendLink : friendLinks) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",friendLink.getId());
            jsonObject.put("blogger",friendLink.getBlogger());
            jsonObject.put("url",friendLink.getUrl());
            result.add(jsonObject);
        }
        return DataMap.success().setData(result);
    }


    /**
     * 根据信息更新友链
     * @param friendLink
     * @return
     */
    @Override
    public DataMap updateFriendLink(FriendLink friendLink) {

        friendLinkMapper.updateFriendLink(friendLink);
        return DataMap.success(CodeType.UPDATE_FRIEND_LINK_SUCCESS);
    }

    /**
     * 添加友链
     * @param friendLink
     * @return
     */
    @Override
    public DataMap addFriendLink(FriendLink friendLink) {
        if (friendLinkMapper.selectFriendLinkIsExist(friendLink) != null){
            return DataMap.fail(CodeType.FRIEND_LINK_EXIST);
        }
//        friendLink.getBlogger();
//        friendLink.getUrl();
        friendLinkMapper.addFriendLink(friendLink);
        return DataMap.success(CodeType.ADD_FRIEND_LINK_SUCCESS);
    }

    /**
     * 根据id删除友链
     * @param id
     * @return
     */
    @Override
    public DataMap deleteFriendLinkById(Integer id) {
        if (id == null){
            return DataMap.fail();
        }
        friendLinkMapper.deleteFriendLinkByIdDao(id);
        return DataMap.success(CodeType.DELETE_FRIEND_LINK_SUCCESS);
    }
}
